package com.df.springmvc.common.util;

import java.io.PrintWriter;
import java.net.URLEncoder;
import java.util.HashMap;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import com.df.springmvc.common.bean.MsgBean;
import com.google.gson.Gson;

public class WebUtil{
	/**
	 * 展示二进制文件内容
	 * @param response
	 * @param bean
	 */
	public static void image(HttpServletResponse response,MsgBean bean){
		try{
			response.setContentType("application/octet-stream; charset=utf-8");
			response.setCharacterEncoding("utf-8");
			ServletOutputStream out=null;
			try{
				HashMap<String,Object> file=(HashMap<String,Object>)bean.getContent();
				String filename="" + file.get("filename");
				Object content=file.get("content");
				out=response.getOutputStream();
				response.setHeader("content-disposition","attachment;filename=" + URLEncoder.encode(filename,"UTF-8"));
				if(content instanceof byte[]){
					byte[] b=(byte[])content;
					out.write(b);
				}
			}catch(Exception e){
				// TODO Auto-generated catch block
				// e.printStackTrace();
			}finally{
				out.close();
			}
		}catch(Exception e){
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	public static void json(HttpServletResponse response,MsgBean bean){
		try{
			response.setContentType("application/Json; charset=utf-8");
			response.setCharacterEncoding("utf-8");
			PrintWriter out=null;
			try{
				out=response.getWriter();
				out.write(new Gson().toJson(bean));
			}catch(Exception e){
				// TODO Auto-generated catch block
				// e.printStackTrace();
			}finally{
				out.close();
			}
		}catch(Exception e){
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	public static void script(HttpServletResponse response,String info){
		try{
			response.setContentType("text/html; charset=utf-8");
			response.setCharacterEncoding("utf-8");
			PrintWriter out=null;
			try{
				out=response.getWriter();
				String temp="<script type=\"text/javascript\">" + info + "</script>";
				org.apache.log4j.Logger.getLogger(WebUtil.class).debug("调用脚本:" + temp);
				out.write(temp);
			}catch(Exception e){
				// TODO Auto-generated catch block
				// e.printStackTrace();
			}finally{
				out.close();
			}
		}catch(Exception e){
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	public static void html(HttpServletResponse response,String info){
		try{
			response.setContentType("text/html; charset=utf-8");
			response.setCharacterEncoding("utf-8");
			PrintWriter out=null;
			try{
				out=response.getWriter();
				String temp="<body>" + info + "</body>";
				out.write(temp);
			}catch(Exception e){
				// TODO Auto-generated catch block
				// e.printStackTrace();
			}finally{
				out.close();
			}
		}catch(Exception e){
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}
